﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace igflow.Components
{
    /// <summary>
    /// A Component which renders a mesh
    /// </summary>
    public class igMeshRenderer : igComponent
    {
        public List<Mesh> meshes = new List<Mesh>();
        BasicEffect effect;
        public override void Init()
        {
            effect = new BasicEffect(World.Graphics.GraphicsDevice, null);
            //quadEffect.EnableDefaultLighting();
            effect.World = Matrix.Identity;

            base.Init();
        }

        float t = 0;
        int dir = 1;
        public override void Draw()
        {
            /*
             * foreach(Mesh mesh in meshes)
            {
                Renderer.Draw(mesh,gameObject);
            }*/
            // stick the mesh in the batch;

            Mesh mesh = meshes[0];
            BasicEffect currentEffect = effect;
            effect.VertexColorEnabled = true;
            if (mesh.Textures != null)
            {
                effect.Texture = mesh.Textures[0];
                effect.TextureEnabled = true;
                effect.GraphicsDevice.RenderState.AlphaBlendEnable = true;
                effect.GraphicsDevice.RenderState.AlphaBlendEnable = true;
                effect.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
                effect.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
            }
            //effect.GraphicsDevice.RenderState.FillMode = FillMode.WireFrame;
            effect.GraphicsDevice.RenderState.CullMode = CullMode.None;
            currentEffect.GraphicsDevice.VertexDeclaration = mesh.vertexDeclaration;
            currentEffect.View = gameObject.WorldMatrix *  CameraManager.CurrentCamera.View;
            currentEffect.Projection = CameraManager.CurrentCamera.Projection;
            currentEffect.World = Matrix.Identity;
            currentEffect.Begin();
            foreach (EffectPass pass in currentEffect.CurrentTechnique.Passes)
            {
                pass.Begin();

                World.Graphics.GraphicsDevice.DrawUserIndexedPrimitives
                   <VertexPositionColorTexture>(
                   PrimitiveType.TriangleList,
                   mesh.GetVertices(), 0, mesh.GetVertices().Length,
                   mesh.GetIndexes(), 0, mesh.GetIndexes().Length / 3);

                pass.End();
            }
            currentEffect.End();
        }
    }
}
